package com.my.pdfexplorer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.my.pdfexplorer.adapter.ImageThumbnailRecyclerAdapter;
import com.my.pdfexplorer.databinding.ActivityThumbnailBinding;
import com.my.pdfexplorer.utils.BitmapMemoryCacheHelper;
import com.snakeway.pdflibrary.util.SizeF;
import com.snakeway.pdfviewer.PDFView;
import com.snakeway.pdfviewer.RenderingCustomHandler;
import com.snakeway.pdfviewer.listener.OnLoadCompleteListener;
import com.snakeway.pdfviewer.util.FitPolicy;

import java.util.ArrayList;
import java.util.List;

public class ThumbnailActivity extends BaseActivity<ActivityThumbnailBinding> implements OnLoadCompleteListener {
    public static String RESULT_PAGE_KEY = "page";

    private View.OnClickListener onClickListener;
    private PDFView.Configurator configurator;
    private BitmapMemoryCacheHelper bitmapMemoryCacheHelper = new BitmapMemoryCacheHelper();

    private String filePath;
    private String filePassword;
    private int selectPage;


    public static void openThumbnailActivity(Activity activity, String filePath, String filePassword, int selectPage, int requestCode) {
        Intent intent = new Intent(activity, ThumbnailActivity.class);
        intent.putExtra(MainActivity.FILE_PATH_KEY, filePath);
        intent.putExtra(MainActivity.FILE_PASSWORD_KEY, filePassword);
        intent.putExtra(MainActivity.SELECT_PAGE_KEY, selectPage);
        if (requestCode == -1) {
            activity.startActivity(intent);
        } else {
            activity.startActivityForResult(intent, requestCode);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        filePath = intent.getStringExtra(MainActivity.FILE_PATH_KEY);
        filePassword = intent.getStringExtra(MainActivity.FILE_PASSWORD_KEY);
        selectPage = intent.getIntExtra(MainActivity.SELECT_PAGE_KEY, 0);
        initAll();
    }

    @Override
    protected ActivityThumbnailBinding getViewBinder() {
        return ActivityThumbnailBinding.inflate(getLayoutInflater());
    }

    @Override
    public void initHandler() {
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void initUi() {
        onClickListener();
    }

    @Override
    public void initConfigUi() {
        viewBinding.layoutAppbar.textViewToolbarLeft.setText(getString(R.string.activity_thumbnail_title));
        openPdf(filePath, filePassword);
    }

    @Override
    public void initHttp() {
    }

    @Override
    public void initOther() {

    }

    private void onClickListener() {
        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.imageViewBack:
                        doBack();
                        break;
                    default:
                        break;
                }
            }
        };
        viewBinding.layoutAppbar.imageViewBack.setOnClickListener(onClickListener);
    }

    private void openPdf(@NonNull String assetFileName, @Nullable String password) {
        configurator = viewBinding.pdfView.fromAsset(assetFileName);
        configurator.password(password)
                .swipeHorizontal(true)
                .pageSnap(false)
                .onLoad(this)
                .pageFitPolicy(FitPolicy.HEIGHT)
                .enableAnnotationRendering(false)
                .linkHandler(null)
                .setSupportCustomRendering(true)
                .load();
    }


    @Override
    public void doBack() {
        super.doBack();
        finish();
    }

    @Override
    public void onDestroy() {
        if (viewBinding.pdfView != null) {
            viewBinding.pdfView.recycle();
        }
        super.onDestroy();
    }

    @Override
    public void loadComplete(int nbPages) {
        viewBinding.gridView.setLayoutManager(new GridLayoutManager(this, 3));
        viewBinding.gridView.setAdapter(new ImageThumbnailRecyclerAdapter(ThumbnailActivity.this, viewBinding.pdfView, new ImageThumbnailRecyclerAdapter.OnImageThumbnailItemClickListener() {
            @Override
            public void onItemClick(View view, int position, RenderingCustomHandler.RenderingCustomPageInfo renderingCustomPageInfo) {
                ThumbnailActivity.choosePage(ThumbnailActivity.this, position);
            }
        }, bitmapMemoryCacheHelper, getAllRenderingCustomPageInfos(viewBinding.pdfView), selectPage, -1));
//        viewBinding.gridView.setAdapter(new ImageThumbnailAdapter(ThumbnailActivity.this, bitmapMemoryCacheHelper, getAllRenderingCustomPageInfos(viewBinding.pdfView), 0));
    }

    public static void getRenderingImages(PDFView pdfView, List<RenderingCustomHandler.RenderingCustomPageInfo> pages, RenderingCustomHandler.OnRenderingCustomListener onRenderingCustomListener) {
        if (pages == null) {
            return;
        }
        RenderingCustomHandler.RenderingCustomTask renderingCustomTask = new RenderingCustomHandler.RenderingCustomTask(pages, true, false, false, onRenderingCustomListener);
        renderingCustomTask.thumbnailRatio = 0.2f;
        pdfView.addRenderingCustomTask(renderingCustomTask);
    }

    public static void choosePage(BaseActivity baseActivity, int page) {
        Intent intent = new Intent();
        intent.putExtra(RESULT_PAGE_KEY, page);
        baseActivity.setResult(RESULT_OK, intent);
        baseActivity.finish();
    }

    public static List<RenderingCustomHandler.RenderingCustomPageInfo> getAllRenderingCustomPageInfos(PDFView pdfView) {
        int pageCount = pdfView.getPageCount();
        List<RenderingCustomHandler.RenderingCustomPageInfo> pages = new ArrayList<>();
        for (int i = 0; i < pageCount; i++) {
            SizeF size = pdfView.getPageSize(i);
            pages.add(new RenderingCustomHandler.RenderingCustomPageInfo(i, size.getWidth(), size.getHeight(), new RectF(0, 0, 1, 1)));
        }
        return pages;
    }
}
